/* Functionality for the Calendar page */
var Calendar = {
	hasTimezone:true,
	events:{}, // used by setTimelineEvents()
	eventDescriptions:{}, // used by setTimelineEvents()
	init:function(){
		Calendar.activateTimeline();
		Calendar.activateEvents();
		Calendar.setTodayButtons();
		Calendar.initFilters();
	},
	showMonths:function(){
		$('.controls-months').removeClass("hidden");
		$('.controls-buttons').addClass("hidden");
	},
	showDates:function(){
		$('.controls-day').removeClass("hidden");
		$('.controls-buttons').addClass("hidden");
	},
	showYears:function(){
		$('.controls-year').removeClass("hidden");
		$('.controls-buttons').addClass("hidden");
	},
	activateTimeline:function(){ // set events to all the timeline buttons
		var $timelineMonth = $('#timeline-month');
		$timelineMonth.off();
		$timelineMonth.on('click',function(){
			Calendar.showMonths();
		});
		
		var $timelineDay = $('#timeline-day');
		$timelineDay.off();
		$timelineDay.on('click',function(){
			Calendar.showDates();
		});
		
		var $timelineYear = $('#timeline-year');
		$timelineYear.off();
		$timelineYear.on('click',function(){
			Calendar.showYears();
		});
		
		var $controlsMonths = $('.controls-months button');
		$controlsMonths.off();
		$controlsMonths.on('click',function(){
			Calendar.setMonth(this);
		});
		
		var $controlsDay = $('.controls-day button');
		$controlsDay.off();
		$controlsDay.on('click',function(){
			Calendar.setDay(this);
		});
		
		var $controlsYear = $('.controls-year button');
		$controlsYear.off();
		$('.controls-year button').on('click',function(){
			Calendar.setYear(this);
		});
		
		var $timelineToday = $('#timeline-today');
		$timelineToday.off();
		$timelineToday.on('click',function(){
			var date = $('[name=control-today]').val().split('/');
			Calendar.showDate(date[0],date[1],date[2]);
		});
	},
	loadMoreEvents:function(button){
		var $button = $(button);
		$button.attr('onclick','');
		$button.html('<i class="fa fa-spinner fa-spin"></i>Loading...');
		var date = $button.attr('date');
		Ajax.run({
			method:"calendarView.renderCalendarDays",
			onsuccess:function(data){
				$button.replaceWith(data);
			},
			args:{
				date:date,
				requested_date:"01/01/1980",
				days_before_show:0
			}
		});
	},
	saveEvent:function(button){
		var $save = $(button);
		var $form = $save.closest('form[name=event_form]');

		var args = Main.formToStruct($form);
		if(Calendar.validateEvent($form.get(0))){
			// show loading
			Calendar.cancelEventEdit($save);
			var $event = $save.closest('.event');
			var $edit = $event.find('button.event-edit');
			$edit.parent().css({overflow:"hidden"});
			$edit.replaceWith('<i class="fa fa-spinner fa-spin event-saving"><i/>');
			Ajax.run({
				method:"calendarService.saveEvent",
				onsuccess:function(data){
					Calendar.renderDay(args.date);
				},
				args:args
			});
		}
	},
	_deleteEvent:function(button){
		var $save = $(button);
		var $form = $save.closest('form[name=event_form]');
		var args = Main.formToStruct($form);
		if(!confirm('Delete '+args.description.trim()+'?')){
			return;
		}
		// show loading
		Calendar.cancelEventEdit($save);
		var $event = $save.closest('.event');
		var $edit = $event.find('button.event-edit');
		$edit.parent().css({overflow:"hidden"});
		$edit.replaceWith('<i class="fa fa-spinner fa-spin event-saving"><i/>');
		Ajax.run({
			method:"calendarService.deleteEvent",
			onsuccess:function(data){
				Calendar.renderDay(args.date);
			},
			args:{
				eventID:args.id,
				google_event_id:args.google_event_id,
				google_calendar_id:args.google_calendar_id
			}
		});
	},
	deleteEvent:function(that){
		var $this = $(that);
		var $event = $this.closest('.event');
		var $cancel = $event.find('.event-cancel');
		var $save = $event.find('.event-save');
		var id = $event.find('input[name=id]').val();
		var google_event_id = $event.find('input[name=google_event_id]').val() || "";
		var google_calendar_id = $event.find('input[name=google_calendar_id]').val() || "";
		var requested_date = $event.find('input[name=requested_date]').val();
		var redirect = $event.find('input[name=redirect]').val();
		if($this.hasClass('real')){
			Calendar._deleteEvent($this);
		} else {
			$cancel.fadeOut(150);
			$save.fadeOut(150);
			$this.fadeOut(150,function(){
				$this.addClass('real');
				$this.text('Really Delete?');
				$this.fadeIn(150);
				setTimeout(function(){
					$this.fadeOut(150,function(){
						$cancel.fadeIn(150);
						$save.fadeIn(150);
						$this.removeClass('real');
						$this.text('delete');
						$this.fadeIn(150);
					});
				},2500);
			});
		}
	},
	activateEvents:function(){
		Time.init();
		// event edit button
		var $buttonEventEdit = $('button.event-edit');
		$buttonEventEdit.off();
		$buttonEventEdit.on('click',function(){
			Calendar.showEventEdit(this);
		});
		// event cancel edit button
		var $buttonEventCancel = $('button.event-cancel');
		$buttonEventCancel.off();
		$buttonEventCancel.on('click',function(){
			Calendar.cancelEventEdit(this);
		});
		
		var $buttonEventAdd = $('button.event-add');
		$buttonEventAdd.off();
		$buttonEventAdd.on("click",function(){
			var $day = $(this).closest('.widget.day');
			var $event = $day.find('.event.hidden');
			var $noEvents = $day.find('.no-events');
			$noEvents.addClass('hidden');
			$event.removeClass('hidden');
			Calendar.showEventEdit($event.find('.event-edit'));
		});
		
		// event category button brings up category
		var $buttonEventCategoryButton = $('button.event-category-button');
		$buttonEventCategoryButton.off();
		$buttonEventCategoryButton.on('click',function(){
			Calendar.showCategoryPicker(this);
		});
		
		// select event category
		var $buttonEventCategorySelectButton = $('button.event-category-select-button');
		$buttonEventCategorySelectButton.off();
		$buttonEventCategorySelectButton.on('click',function(){
			Calendar.selectCategory(this);
		});
		
		// event category input affects buttons
		var $inputCategories = $('input[name=categories]');
		$inputCategories.off();
		$inputCategories.on('keyup',function(){
			var $this = $(this);
			var text = $(this).val();
			if(text == ""){
				text = "Category"
			}
			$this.next().text(text);
		});
	},
	setTodayButtons:function(){
		var today = $("[name=control-today]").val();
		todayArray = today.split('/');
		$('.controls-months button[value='+todayArray[0]+']').addClass('current');
		$('.controls-day button[value='+todayArray[1]+']').addClass('current');
		$('.controls-year button[value='+todayArray[2]+']').addClass('current');
	},
	setMonth:function(that){
		var $month = $('#timeline-month');
		var $this = $(that);
		$month.text($this.text());
		$month.attr('value',$this.attr('value'))
		$('.controls-months').addClass('hidden');
		$('.controls-buttons').removeClass("hidden");
		Calendar.filterDaysInMonth(+$(that).attr('value'));
		Calendar.setDate();
	},
	setDay:function(that){
		var $day = $('#timeline-day');
		var $this = $(that);
		$day.text($this.text());
		$day.attr('value',$this.attr('value'));
		$('.controls-day').addClass('hidden');
		$('.controls-buttons').removeClass("hidden");
		Calendar.setDate();
	},
	setYear:function(that){
		var $year = $('#timeline-year');
		var $this = $(that);
		$year.text($this.text());
		$year.attr('value',$this.attr('value'));
		$('.controls-year').addClass('hidden');
		$('.controls-buttons').removeClass("hidden");
		Calendar.setDate();
	},
	filterDaysInMonth:function(month){
		$('.controls-day button').removeClass('hidden');
		var $day = $('#timeline-day');
		var currentDay = +$day.attr('value');
		if(month == 4 || month == 6 || month == 9 || month == 11){
			$('.controls-day button[value=31]').addClass('hidden');
			if(currentDay == 31){
				$day.text(30);
				$day.attr('value',30);
			}
		} else if(month == 2){
			$('.controls-day button[value=31]').addClass('hidden');
			$('.controls-day button[value=30]').addClass('hidden');
			var year = +$('#timeline-year').attr('value');
			if(year % 4 != 0){
				$('.controls-day button[value=29]').addClass('hidden');
				if(currentDay > 28){
					$day.text(28);
					$day.attr('value',28);
				}
			} else {
				if(currentDay > 29){
					$day.text(29);
					$day.attr('value',29);
				}
			}
		}
	},
	setDate:function(mm,dd,yyyy){
		var mm = mm || "";
		var dd = dd || "";
		var yyyy = yyyy || "";
		if(mm == ""){
			mm = $('#timeline-month').attr('value');
		}
		if(dd == ""){
			dd = $('#timeline-day').attr('value');
		}
		if(yyyy == ""){
			yyyy = 	$('#timeline-year').attr('value');
		}
		var date = mm + '/' + dd + '/' + yyyy;
		$('input[name=control-value]').val(date);
		Ajax.run({
			method:"calendarView.renderTimeline",
			onsuccess:function(data){
				$('.timeline-container').html(data);
				//ajax in new set of days
				var $days = $('.widget.day');
				URL.setValue('date',date);
				$days.fadeOut(150);
				Calendar.renderDays(date);
				HoverBubble.init();
			},
			args:{date:date}
		});
		if(date != $('[name=control-today]').val()){
			$('#timeline-today').fadeIn(150);
		} else {
			$('#timeline-today').fadeOut(150);
		}
		// set refresh_calendar's date
		$('form[name=refresh_calendar]').find('input[name=date]').val(mm+'/'+dd+'/'+yyyy);
	},
	renderDay:function(date){ // load and replace a single day from server
		var requested_date = $("[name=requested_date]:first").val();
		Ajax.run({
			method:"calendarView.renderCalendarDay",
			onsuccess:function(data){
				$('.widget.day[date="'+date+'"]').replaceWith(data);
				Main.activateTextareaResize();
				Calendar.activateEvents();
				Calendar.applyFilters();
				// update the url to the new date, in case of refresh
				URL.setValue('date',date);
				// refresh the Kalendar, since something must have changed.
				Ajax.run({
					method:"leftView.renderCalendar",
					onsuccess:function(data){
						$('#module-left-calendar-div').replaceWith(data);
					}
				});
				// refresh teh Secretary
				Secretary.reload();
			},
			args:{date:date,requested_date:requested_date}
		});
	},
	renderDays:function(date){
		if(Calendar.hasTimezone){
			$('.more-events').remove();
			Ajax.run({
				method:"calendarView.renderCalendarDays",
				onsuccess:function(data){
					$('.widget.day').remove();
					$('.widget.options').after(data);
					Main.activateTextareaResize();
				},
				args:{date:date}
			});
		}
	},
	showDate:function(mm,dd,yyyy){
		var $year = $('#timeline-year');
		var $day = $("#timeline-day");
		var $month = $("#timeline-month");

		$year.text(yyyy);
		$year.attr('value',yyyy);
		$day.text(+dd);
		$day.attr('value',dd);
		$month.attr('value',mm);
		$month.text($('.controls-months button[value='+mm+']').text());
		
		Calendar.setDate(mm,dd,yyyy);
	},
	showEventEdit:function(that){
		var $event = $(that).closest('.event');
		$event.find('.event-add').addClass('hidden');
		$event.addClass('edit');
		$(that).closest('.widget').addClass('editing');
		var $textarea = $event.find('textarea[name=description]');
		Main.resizeTextarea($textarea.get(0));
		$textarea.focus();
	},
	cancelEventEdit:function(that){
		var $event = $(that).closest('.event');
		var $day = $event.closest('.widget.day');
		$day.find('.event:last').addClass('hidden');
		$day.find('.event-add').removeClass('hidden');
		$event.removeClass('edit');
		$(that).closest('.widget').removeClass('editing');
		// restore category if it has been changed but not saved
		var realCat = $event.attr('category');
		$event.removeClass('cat1').removeClass('cat2').removeClass('cat3').removeClass('cat4');
		$event.addClass('cat'+realCat);
		// find the real name and restore to button
		var realCatName = $event.find('button.cat'+realCat).attr('category');
		$event.find('.event-category-button').text(realCatName);
		// if the day has no events, restore .no-events
		if($day.find('.event').not('.event-new').length== 0){
			$day.find('.no-events').removeClass('hidden');
		}
	},
	showStop:function(that){
		var $this = $(that);
		var $setStop = $this.prev();
		$this.addClass('hidden');
		$setStop.removeClass('hidden');
		$setStop.click();
	},
	showTimepicker:function(that){
		var $this = $(that);
		var $eventEdit = $this.closest('.event-edit');
		var $event = $eventEdit.parent();
		var which = $this.attr('class').split(' ')[0].split('-')[1];
		var $timepicker = $event.find('div.timepicker[name='+which+']');
		$event.find('.h30').removeClass('selected');
		$eventEdit.addClass('hidden');
		$timepicker.removeClass('hidden');
		// filter stop time on open
		if($this.hasClass('event-stop')){
			var $startPicker = $event.find('div.timepicker[name=start]');
			Time.filterStoptime($startPicker,'stop');
		}
	},
	showCategoryPicker:function(that){
		var $this = $(that);
		var $event = $this.closest('.event');
		var $edit = $event.find('.event-edit');
		var $category = $event.find('.event-category');
		$category.removeClass('hidden');
		$edit.addClass('hidden');
	},
	selectCategory:function(that){
		var $this = $(that);
		var $event = $this.closest('.event');
		var $edit = $event.find('.event-edit');
		var $category = $event.find('.event-category');
		var $categoryInput = $event.find('input[name=category]');
		var $categoryText = $event.find(".category-text");
		var value = $this.attr('value');
		$category.addClass('hidden');
		$edit.removeClass('hidden');
		$categoryInput.val(value);
		$event.removeClass('cat1').removeClass('cat2').removeClass('cat3').removeClass('cat4').removeClass('cat5').removeClass('cat6');
		$event.addClass('cat'+value);
		// update the button text
		var $button = $event.find('.event-category-button');
		var text = $this.text();
		if(+value == 0){
			text = 'category';
		}
		$button.find('span').text(text);
		// update category text
		$categoryText.text(text);
	},
	validateEvent:function(that){
		var $this = $(that);
		var $textarea = $this.find('textarea');
		var value = $textarea.val();
		if(value.length > 0){
			$textarea.removeClass('validation-failed');
			return true;
		} else {
			$textarea.addClass('validation-failed');
			return false;
		}
	},
	setTimelineEvents:function(){
		// clean up the timeline
		$('.timeline-event').remove();
		for(var date in Calendar.events){
			var $date = $('td[date='+date+'] .timeline-events');
			for(var i = 0; i < Calendar.events[date].length; i++){
				$date.append('<div class="timeline-event cat'+Calendar.events[date][i]+'"></div>');
			}
			try{
				var description = Calendar.eventDescriptions[date].replace(/(?:\r\n|\r|\n)/g, '<br />');;
				$('td[date='+date+']').attr('bubble',Calendar.eventDescriptions[date]);
			}catch(e){/*do nothing*/}
		}
		HoverBubble.init();
	},
	showGoogleInfo:function(that){
		var $this = $(that);
		if($this.attr('expanded') != 'yes' && $this.attr('animate') != 'yes'){
			$this.attr('expanded','yes');
			$this.attr('animate','yes');
			$this.animate({height:'25px',width:'175px',borderTopLeftRadius:'5px'},500,'easeInOutQuart',function(){
				$this.attr('animate','no');
			});
		}
	},
	hideGoogleInfo:function(that){
		var $this = $(that).closest('.event-google');
		if($this.attr('expanded') == 'yes' && $this.attr('animate') == 'no'){
			$this.attr('expanded','no');
			$this.attr('animate','yes');
			$this.animate({height:'5px',width:'5px',borderTopLeftRadius:'6px'},500,'easeInOutQuart',function(){
				$this.attr('animate','no');
			});
		}
	},
	disconnectGoogleCalendar:function(){
		if(confirm("1. Events created using Craftivity will no longer appear in Google.\n\n2. Events imported from Google will no longer appear in Craftivity.\n\nContinue?")){
			$('form[name=disconnect_calendar]').submit();
		}
	},
	connectGoogleCalendar:function(){
		if(confirm("1. Craftivity events will appear in your Google Calendar.\n\n2. Google Calendar events will appear in Craftivity.\n\nContinue?")){
			$('form[name=connect_calendar]').submit();
		}
	},
	initFilters:function(){
		$('.controls-filters button').on('click',function(){
			Calendar.toggleFilter(this);
		});
	},
	hideFilters:function(){
		$('.controls-filters').fadeOut(function(){
			Calendar.updateFilterButtonCount();
			$('#show-filters').fadeIn();
		});
	},
	updateFilterButtonCount:function(){
		var count = $('.controls-filters').find('button.filtered').length;
		var text = "Filter";
		if(count > 0){
			text = count + " Filter";
			if(count > 1){
				text+="s";
			}
		}
		$('#show-filters').text(text);
	},
	toggleFilter:function(that){
		var $this = $(that);
		if($this.hasClass('filtered')){
			$this.removeClass('filtered');
		} else {
			$this.addClass('filtered');
		}
		Calendar.applyFilters();
		Main.throttle(Calendar.updateOptions,'filterUpdate',1200);
	},
	updateOptions:function(){
		var days = "";
		var cats = "";
		$('.controls-filters-day button').each(function(){
			var $this = $(this);
			if($this.hasClass('filtered')){
				if(days != ""){days += ',';}
				days+=$this.val();
			}
		});
		$('.controls-filters-category button').each(function(){
			var $this = $(this);
			if($this.hasClass('filtered')){
				if(cats != ""){cats += ',';}
				cats+=$this.val();
			}
		});
		Ajax.run({
			method:"calendarService.saveFilters",
			onsuccess:function(data){
				//console.log('filters saved');
			},
			args:{
				days:days,
				categories:cats
			}
		});
	},
	applyFilters:function(speed){
		speed = speed || 150;
		$('.controls-filters-day button').each(function(){
			var $this = $(this);
			if($this.hasClass('filtered')){
				$('.widget.day[day='+$this.val()+']').fadeOut(speed);
				$('td[date][day='+$this.val()+'] .td-day').animate({opacity:0.12},speed);
			} else {
				$('.widget.day[day='+$this.val()+']').fadeIn(speed).css('display',"");
				$('td[date][day='+$this.val()+'] .td-day').animate({opacity:1},speed);
			}
		});
		$('.controls-filters-category button').each(function(){
			var $this = $(this);
			if($this.hasClass('filtered')){
				$('.event.cat'+$this.val()).fadeOut(speed);
				$('.timeline-event.cat'+$this.val()).fadeOut(speed);
			} else {
				$('.event.cat'+$this.val()).fadeIn(speed);
				$('.timeline-event.cat'+$this.val()).fadeIn(speed).css('display',"");
			}
		});
	},
	editEventInGoogle:function(link){
		window.open(link,'_blank');
		setTimeout(function(){
			$(window).bind('focus.onReturnFromGoogle',function(){
				$(window).unbind('focus.onReturnFromGoogle');
				$('form[name=refresh_calendar]').submit();
			});
		});

	}
};